<template>
  <div class="login-container">
    <div class="loginForm-wrap">
      <el-tabs
        tab-position="top"
        v-model="activeName"
        class="tabs-wrap"
        @tab-click="changeTab"
      >
        <el-tab-pane name="login">
          <span slot="label" class="loginText">登录</span>
          <el-form ref="ruleLogin" :rules="rules" :model="form" class="form">
            <!-- 用户名 -->
            <el-form-item prop="userName">
              <el-input
                maxlength="15"
                v-model.trim="form.userName"
                placeholder="用户名"
              ></el-input>
            </el-form-item>
            <!-- 密码框 -->
            <el-form-item prop="password">
              <el-input
                maxlength="20"
                ref="pwd"
                :type="isShowPassword ? 'text' : 'password'"
                v-model.trim="form.password"
                placeholder="密码"
              >
                <i
                  @click="isShowPassword = !isShowPassword"
                  slot="suffix"
                  class="iconfont icon-xianshimima"
                  v-if="isShowPassword"
                ></i>
                <i
                  @click="isShowPassword = !isShowPassword"
                  slot="suffix"
                  class="iconfont icon-yincangmima"
                  v-else
                ></i>
              </el-input>
            </el-form-item>
            <!-- 验证码框 -->
            <el-form-item class="code-wrap" prop="code">
              <el-input
                maxlength="5"
                placeholder="验证码"
                v-model.trim="form.code"
                @keydown.enter.native="submitLogin"
              ></el-input>
              <el-image
                v-loading="codeLoading"
                @click="loadCode"
                :src="loginCodeImg"
              ></el-image>
            </el-form-item>

            <div class="checkbox">
              <div class="autoLogin">
                <input type="checkbox" v-model="autoLogin" />自动登录
              </div>
              <div class="remePwd">
                <input type="checkbox" v-model="remePwd" />记住密码
              </div>
            </div>

            <!-- 登录按钮 -->
            <el-button
              class="loginBtn"
              @click="submitLogin"
              :loading="loading"
              type="info"
              >登录</el-button
            >
            <!-- 底部忘记密码和免费注册 -->
            <div class="bottom">
              <span class="forgetPwd">忘记密码</span>
              <span class="register" @click="activeName = 'register'"
                >免费注册</span
              >
            </div>
          </el-form>
        </el-tab-pane>

        <el-tab-pane name="register">
          <span slot="label" class="registerText">注册</span>
          <el-form ref="ruleRegister" :rules="rules" :model="form" class="form">
            <!-- 用户名 -->
            <el-form-item prop="userName">
              <el-input
                maxlength="15"
                v-model.trim="form.userName"
                placeholder="用户名"
              ></el-input>
            </el-form-item>
            <!-- 密码框 -->
            <el-form-item prop="password">
              <el-input
                maxlength="20"
                ref="pwd"
                :type="isShowPassword ? 'text' : 'password'"
                v-model.trim="form.password"
                placeholder="请输入密码"
              >
                <i
                  @click="isShowPassword = !isShowPassword"
                  slot="suffix"
                  class="iconfont icon-xianshimima"
                  v-if="isShowPassword"
                ></i>
                <i
                  @click="isShowPassword = !isShowPassword"
                  slot="suffix"
                  class="iconfont icon-yincangmima"
                  v-else
                ></i>
              </el-input>
            </el-form-item>
            <!-- 确认密码框 -->
            <el-form-item prop="confirmPassword">
              <el-input
                maxlength="20"
                ref="pwd"
                :type="isShowConfirmPassword ? 'text' : 'password'"
                v-model.trim="form.confirmPassword"
                placeholder="确认密码"
              >
                <i
                  @click="isShowConfirmPassword = !isShowConfirmPassword"
                  slot="suffix"
                  class="iconfont icon-xianshimima"
                  v-if="isShowConfirmPassword"
                ></i>
                <i
                  @click="isShowConfirmPassword = !isShowConfirmPassword"
                  slot="suffix"
                  class="iconfont icon-yincangmima"
                  v-else
                ></i>
              </el-input>
            </el-form-item>
            <!-- 验证码框 -->
            <el-form-item class="code-wrap" prop="code">
              <el-input
                maxlength="5"
                placeholder="验证码"
                v-model.trim="form.code"
                @keydown.enter.native="submitRegister"
              ></el-input>
              <el-image
                v-loading="codeLoading"
                @click="loadCode"
                :src="registerCodeImg"
              ></el-image>
            </el-form-item>

            <!-- 注册按钮 -->
            <el-button
              class="loginBtn"
              @click="submitRegister"
              :loading="loading"
              type="info"
              >立即注册</el-button
            >
            <!-- 底部忘记密码和免费注册 -->
            <div class="bottom" style="justify-content: right">
              <span class="register" @click="activeName = 'login'"
                >已有账号，立即登录</span
              >
            </div>
          </el-form>
        </el-tab-pane>
      </el-tabs>
    </div>
  </div>
</template>

<script>
import { userNameValidator, passwordValidator } from "@/validators/login.js";
import { login, code, register } from "@/api/user.js";
import store from "@/store";

export default {
  name: "LoginIndex",
  components: {},
  props: {},
  data() {
    return {
      activeName: "login", // 默认展示标签页
      form: {
        userName: store.getters.userName || "", // 账号(用户名/手机号)
        password: store.getters.password || "", // 密码
        confirmPassword: "", // 确认密码
        code: "", // 验证码
      },
      autoLogin: false, // 自动登录
      remePwd: false, // 记住密码
      loginCodeImg: "", // 验证码图片
      registerCodeImg: "", // 验证码图片
      codeKey: "", // 标识该用户的key
      isShowPassword: false, // 是否展示密码
      isShowConfirmPassword: false, // 是否展示密码
      loading: false, // 登录loading
      codeLoading: false, // 验证码加载loading
      rules: {
        userName: [{ validator: userNameValidator, trigger: "change" }],
        password: [{ validator: passwordValidator, trigger: "change" }],
        // 给确认密码框绑定多个触发事件
        confirmPassword: [
          {
            validator: this.confirmPasswordValidator,
            trigger: "change",
          },
          {
            validator: this.confirmPasswordValidator,
            trigger: "blur",
          },
        ],
        code: [{ required: true, message: "请输入验证码", trigger: "blur" }],
      },
    };
  },
  created() {
    // 加载验证码
    this.loadCode();
    // 检查是登录还是注册
    this.checkAction();
  },
  mounted() {},
  methods: {
    // 检查是登录还是注册
    checkAction() {
      let action = this.$route.query.action;
      if (action && action === "register") {
        this.activeName = "register";
      }
    },
    // 切换tab
    changeTab() {
      this.loadCode();
      this.form = {
        userName: "", // 账号(用户名/手机号)
        password: "", // 密码
        confirmPassword: "", // 确认密码
        code: "", // 验证码
      };
    },
    // 提交登录表单
    submitLogin() {
      this.$refs["ruleLogin"].validate(async (valid) => {
        if (valid) {
          this.loading = true;
          try {
            let userName = this.form.userName;
            let password = this.form.password;
            const { data } = await login({
              userName: userName,
              password: password,
              code: this.form.code,
              codeKey: this.codeKey,
            });
            if (data.code === 200) {
              this.$message.success("登录成功");
              const token = data.data.Authorization;
              // 检测是否记住密码或自动登录
              this.$store.commit("setUser", {
                token,
                type: { autoLogin: this.autoLogin, remePwd: this.remePwd },
                userName,
                password,
              });

              // 跳转到首页
              this.$router.push("/portal");
            } else {
              this.$message.error(data.msg);
              this.form.code = "";
              this.loadCode();
            }
          } catch (err) {
            console.log("err = " + err);
            this.$message.error("登录失败，请稍后重试！");
          } finally {
            this.loading = false;
          }
        }
      });
    },
    // 提交注册表单
    submitRegister() {
      this.$refs["ruleRegister"].validate(async (valid) => {
        if (valid) {
          this.loading = true;
          try {
            const { data } = await register({
              userName: this.form.userName,
              password: this.form.password,
              confirmPassword: this.form.confirmPassword,
              code: this.form.code,
              codeKey: this.codeKey,
            });
            if (data.code === 200) {
              this.$message.success("注册成功");
              // 将数据保存在vuex
              const token = data.data.Authorization;
              this.$store.commit("setUser", {
                token,
                type: { autoLogin: false, remePwd: false },
                userName: "",
                password: "",
              });
              // 跳转到首页
              this.$router.push("/portal");
            } else {
              if (data.msg) {
                this.$message.error(data.msg);
                this.form.code = "";
                this.loadCode();
              }
            }
          } catch (err) {
            console.log(err);
            this.$message.error("注册失败，请稍后重试！");
          } finally {
            this.loading = false;
          }
        }
      });
    },
    // 获取验证码
    async loadCode() {
      this.codeLoading = true;
      try {
        const { data } = await code();
        this.codeKey = data.data.codeKey;
        if ("login" === this.activeName) {
          this.loginCodeImg = data.data.base64Img;
        } else {
          this.registerCodeImg = data.data.base64Img;
        }
      } catch (err) {
      } finally {
        this.codeLoading = false;
      }
    },
    // 确认密码校验函数
    confirmPasswordValidator(rule, value, callback, c) {
      if (value.length === 0) {
        callback(new Error("请确认密码"));
      } else if (value !== this.form.password) {
        callback(new Error("两次密码不一致"));
      } else {
        callback();
      }
    },
  },
  computed: {},
  watch: {
    /*       
      autoLogin: false, // 自动登录
      remePwd: false, // 记住密码 
    */
    autoLogin(newValue, oldValue) {
      // 点击自动登录，自动勾选记住密码
      if (newValue) {
        this.remePwd = newValue;
      }
    },
    remePwd(newValue, oldValue) {
      // 取消记住密码，自动取消自动登录
      if (!newValue) {
        this.autoLogin = newValue;
      }
    },
  },
};
</script>

<style scoped lang="less">
.login-container {
  height: 100%;
  background-image: url("~@/assets/login-bg.jpg");
  background-size: cover;
  /* 让表单wrap居中 */
  display: flex;
  justify-content: center;
  align-items: center;

  :deep(.loginForm-wrap) {
    /* 让表单居中 */
    display: flex;
    justify-content: center;
    flex-direction: column;
    align-items: center;
    background-color: rgba(255, 255, 255, 0.9);
    width: 350px;
    height: 400px;

    .tabs-wrap {
      /* 设置当前被激活下面横线样式 */
      .el-tabs__active-bar {
        background-color: #ff5d02;
        height: 3px;
        border-radius: 30px;
      }

      /* 设置当前被激活tabs的字体颜色 */
      .is-active > span {
        color: #333333;
        font-weight: bold;
      }

      /* 设置tabs字体颜色 */
      .loginText,
      .registerText {
        font-size: 16px;
        color: #bbbbbb;
      }

      /* 取消tabs的默认宽度样式 */
      .el-tabs__nav-wrap::after {
        width: unset;
      }
    }

    .form {
      /* 记住密码、自动登录 */
      .checkbox {
        input {
          width: 14px;
          height: 14px;
          margin: 0;
          padding: 0;
        }
        display: flex;
        justify-content: space-around;
        font: 14px/1.5 tahoma, arial, "Hiragino Sans GB", "\5b8b\4f53",
          sans-serif;
        margin-bottom: 10px;
        .autoLogin {
          display: flex;
          align-items: center;
        }
        .remePwd {
          display: flex;
          align-items: center;
        }
      }

      .loginBtn {
        background-color: #ffbe9a;
        width: 250px;
      }

      .el-input {
        .el-input__inner {
          width: 250px;
          padding-left: 10px;
        }
      }

      .bottom {
        margin-top: 10px;
        display: flex;
        justify-content: space-between;
        align-items: center;
        color: #ff7e2c;
        font-size: 14px;

        span.forgetPwd,
        span.register {
          cursor: pointer;
        }
      }

      .code-wrap {
        .el-form-item__content {
          height: 40px;
          display: flex;
          justify-content: space-between;
          align-items: center;
          .el-input {
            position: absolute;
            left: 0;
            width: 100px;
            .el-input__inner {
              width: 100px;
            }
          }
          .el-image {
            width: 100px;
            height: 40px;
            position: absolute;
            right: 0;
          }
        }
      }
    }
  }
}
</style>
